package com.zzyweb.rentalcarsys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzyweb.rentalcarsys.entity.Role;
import com.zzyweb.rentalcarsys.entity.UserAccount;
import com.zzyweb.rentalcarsys.entity.UserInfo;
import com.zzyweb.rentalcarsys.entity.relationship.UserAndRole;
import com.zzyweb.rentalcarsys.entity.viewobject.UserVO;
import com.zzyweb.rentalcarsys.exception.BusinessException;
import com.zzyweb.rentalcarsys.exception.ErrorCode;
import com.zzyweb.rentalcarsys.mapper.*;
import com.zzyweb.rentalcarsys.service.UserService;
import com.zzyweb.rentalcarsys.utils.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @author zhiyi
 * @date 10/4/25
 **/
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserAccountMapper userAccountMapper;
    @Autowired
    UserInfoMapper userInfoMapper;

    @Autowired
    UserVOMapper userVOMapper;

    @Autowired
    UserRoleMapper userRoleMapper;

    @Autowired
    RoleMapper roleMapper;
    @Override
    public PageResult<UserVO> getUsers(Long currentPage, Long pageSize, UserVO userVO) {
        Page<UserAccount> page = new Page<>(currentPage, pageSize);
        System.out.println(userVO);

        if (userVO == null) {
            IPage allUser = userInfoMapper.getAllUser(page);
            List<UserVO> list = allUser.getRecords();
            for (UserVO userVO1 : list) {
                List<Role> roles = roleMapper.selectRolesByUserId(userVO1.getId());
                userVO1.setRoles(roles);
                System.out.println(userVO1);
            }
            System.out.println(allUser.getRecords());
            return new PageResult<>(allUser.getCurrent(), allUser.getSize(), allUser.getTotal(), allUser.getRecords());
        } else {
            IPage allUser = userInfoMapper.getAllUserByConditions(page,userVO.getUsername(),userVO.getEmail(),userVO.getPhoneNumber(),userVO.getFullName());
            List<UserVO> list = allUser.getRecords();
            for (UserVO userVO1 : list) {
                List<Role> roles = roleMapper.selectRolesByUserId(userVO1.getId());
                userVO1.setRoles(roles);
                System.out.println(userVO1);
            }
            System.out.println(allUser.getRecords());
            return new PageResult<>(allUser.getCurrent(), allUser.getSize(), allUser.getTotal(), allUser.getRecords());
        }

    }

    @Override
    @Transactional
    public void deleteUserBatch(String ids) {
        if (!StringUtils.hasText(ids)) throw new BusinessException(ErrorCode.FAIL);
        String[] idsArr = ids.split(",");
        int row1 = 0;
        int row2 = 0;
        for (String idStr: idsArr) {
            row1 += userAccountMapper.deleteById(Long.parseLong(idStr));
            QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", Long.parseLong(idStr));
            row2 += userInfoMapper.delete(queryWrapper);
        }
        if (row1 != row2 || row1 != idsArr.length) {
            throw new BusinessException(ErrorCode.FAIL);
        }
    }

    @Override
    public void deleteUser(String id) {
        if (!StringUtils.hasText(id)) throw new BusinessException(ErrorCode.FAIL);
        int row1 = userAccountMapper.deleteById(Long.parseLong(id));
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", Long.parseLong(id));
        int row2 = userInfoMapper.delete(queryWrapper);
        if (row1 != row2 || row1 != 1)  throw new BusinessException(ErrorCode.FAIL);
    }

    @Override
    @Transactional
    public void addUser(UserVO userVO) {
        UserAccount userAccount = new UserAccount();
        userAccount.setUsername(userVO.getUsername());
        userAccount.setPassword(DigestUtils.md5DigestAsHex("test123".getBytes()));
        userAccount.setEmail(userVO.getEmail());
        userAccount.setPhoneNumber(userVO.getPhoneNumber());
        userAccount.setIsDelete(0);
        userAccountMapper.insert(userAccount);

        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(userAccount.getId());
        userInfo.setFullName(userVO.getFullName());
        userInfo.setIdentityNumber(userVO.getIdentityNumber());
        userInfo.setIsDelete(0);
        userInfo.setProfilePicture(userVO.getProfilePicture());
        userInfoMapper.insert(userInfo);
    }

    @Override
    public void modifyUser(UserVO userVO) {
        UserAccount userAccount = new UserAccount();
        userAccount.setId(userVO.getId());
        userAccount.setUsername(userVO.getUsername());
        userAccount.setPassword(DigestUtils.md5DigestAsHex("test123".getBytes()));
        userAccount.setEmail(userVO.getEmail());
        userAccount.setPhoneNumber(userVO.getPhoneNumber());
        userAccount.setIsDelete(0);
        userAccountMapper.updateById(userAccount);

        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(userAccount.getId());
        userInfo.setFullName(userVO.getFullName());
        userInfo.setIdentityNumber(userVO.getIdentityNumber());
        userInfo.setIsDelete(0);
        userInfo.setProfilePicture(userVO.getProfilePicture());
        UpdateWrapper<UserInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("user_id", userVO.getId());
        userInfoMapper.update(userInfo, updateWrapper);

    }

    @Override
    public void setRole(String userId, Integer roleId) {
        UserAndRole userAndRole = new UserAndRole();
        userAndRole.setRoleId(roleId);
        userAndRole.setUserId(Long.parseLong(userId));
        userRoleMapper.insert(userAndRole);
    }

    @Override
    public void modifyUserRole(String roleIds, String userId) {
        if (!StringUtils.hasText(userId)||!StringUtils.hasText(roleIds)) throw new BusinessException(ErrorCode.FAIL);
        userRoleMapper.deleteByUserId(Long.parseLong(userId));
        String[] roleIdArr = roleIds.split(",");
        UserAndRole userAndRole = new UserAndRole();
        for (int i = 0; i < roleIdArr.length; i++) {
            userAndRole.setId(null);
            userAndRole.setRoleId(Integer.parseInt(roleIdArr[i]));
            userAndRole.setUserId(Long.parseLong(userId));
            userRoleMapper.insert(userAndRole);
        }
    }

    @Override
    public UserVO getUserByUserId(Long userId) {
        UserVO userVO = userVOMapper.selectUserVO(userId);
        return userVO;
    }

}
